<?php

namespace app\admin\controller;

use app\common\controller\AdminController;

//引入外部函数
use app\common\model\hfztcy\LibMember;
use app\common\model\hfztcy\LibNotifyPay;
use app\common\model\hfztcy\LibOrder;
use app\common\model\hfztcy\LibOrderOneYuan;
use app\common\model\hfztcy\LibOrderRedMother;
use app\common\model\hfztcy\LibOrderRefund;
use app\common\model\hfztcy\LibOrderVip;
use app\common\model\hfztcy\LibOrderVipAuth;
use app\common\model\hfztcy\LibStore;
use app\common\model\hfztcy\LibUserVideoAuth;
use app\common\model\LibUser;
use common\Common;


/**
 * 订单列表
 * @name Order.php
 * @package hfztcy
 * @category controller
 * @author rxy
 * @version 1.0
 * @copyright CHANGE INC
 * @since 2020-6-5
 */
class Order extends AdminController
{
    protected $lib_order;
    protected $lib_user;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->lib_order = new LibOrder();
        $this->lib_user = new LibUser();
        $this->rightVerify(session('admin'), url("admin/Login/login"));
        parent::__construct();
    }

    /**
     * 一元订单-列表页
     */
    function oneYuanOrderList()
    {
        $this->getSetMenu($this);
        $this->log(__CLASS__, __FUNCTION__, "一元订单-列表页", 1, 'view');
        return $this->fetch('Order/oneYuanOrderList/orderList');
    }

    /**
     * VIP套餐订单-列表页
     */
    function vipPackageOrderList()
    {
        $this->getSetMenu($this);
        $this->log(__CLASS__, __FUNCTION__, "VIP套餐订单-列表页", 1, 'view');
        return $this->fetch('Order/vipPackageOrderList/orderList');
    }

    /**
     * VIP套餐订单-列表页
     */
    function vipAuthOrderList()
    {
        $this->getSetMenu($this);
        $this->log(__CLASS__, __FUNCTION__, "VIP套餐订单-列表页", 1, 'view');
        return $this->fetch('Order/vipAuthOrderList/orderList');
    }

    /**
     * 红娘-列表页
     */
    function vipRedMotherOrderList()
    {
        $this->getSetMenu($this);
        $this->log(__CLASS__, __FUNCTION__, "红娘-列表页", 1, 'view');
        return $this->fetch('Order/redMotherOrderList/orderList');
    }

    /**
     * 红娘-退款-列表页
     */
    function redMotherOrderRefundList()
    {
        $this->getSetMenu($this);
        $this->log(__CLASS__, __FUNCTION__, "红娘-退款-列表页", 1, 'view');
        return $this->fetch('Order/redMotherOrderRefundList/orderList');
    }

    /**
     * 栏目认证-退款-列表页
     */
    function vipAuthOrderRefundList()
    {
        $this->getSetMenu($this);
        $this->log(__CLASS__, __FUNCTION__, "栏目认证-退款-列表页", 1, 'view');
        return $this->fetch('Order/vipAuthOrderRefundList/orderList');
    }

    /**
     * 删除
     */
    function deleteOrder()
    {
        $id = input("id");
        $result = $this->lib_order->deleteOrder(["id" => $id]);
        echo json_encode($result);
    }

    /**
     * 分页查询
     */
    function pagingOrder()
    {
        $args = input();
        $page = $this->getPageInfo();
        $index = (int)$args['type'];
        $method = [
            'app\common\model\hfztcy\LibOrderOneYuan',//一元订单模型
            'app\common\model\hfztcy\LibOrderVip',//vip套餐订单模型
            'app\common\model\hfztcy\LibOrderVipAuth',//视频认证订单模型
            'app\common\model\hfztcy\LibOrderRedMother',//红娘认证订单模型
            'app\common\model\hfztcy\LibOrderRefund',//订单退款
        ];
        $result = call_user_func(array($method[$index],'getOrderList'),$args,$page);
        echo json_encode($result);
    }

    /**
     * Info: 分配门店
     * Date: 2022/11/9 15:38
     */
    function assignStore ()
    {
        $order_id = input('order_id',0);
        $store_id = input('store_id',0);

        $userModel = new LibUser();
        $memberModel = new LibMember();
        $orderModel = new LibOrder();
        $findRes = $orderModel->findOrder(['id' => $order_id]);
        if ($findRes['errorCode'] == 1) {
            echo json_encode(Common::errorArray(1,'订单不存在',false));die();
        }
        $findUserRes = $userModel->findUser(['id' => $findRes['data']['user_id']]);
        if ($findUserRes['errorCode'] == 1) {
            echo json_encode(Common::errorArray(1,'用户不存在',false));die();
        }
        $openid = $findUserRes['data']['account'];
        $code = $findRes['data']['code'];
        $findMemberRes = $memberModel->findMember(['user_id' => $findRes['data']['user_id']]);
        //$username = $findMemberRes['data']['username'].'(昵称：'.$findUserRes['data']['nick_name'].')';

        $storeModel = new LibStore();
        $findRes = $storeModel->findStore(['id' => $store_id]);
        if ($findRes['errorCode'] == 1) {
            echo json_encode(Common::errorArray(1,'门店不存在',false));die();
        }
        $template_id = "z35XzIuxUz5dCQHXWSmxt9QG-T9-5n4IdHqpXrgeP7Y";
        // 给用户发送模板消息
        $data4 = [
            'first'=>array('value'=>'缘份驿站提醒您，已分配门店', 'color'=>'#173177'),
            'keyword1'=>array('value'=>date('Y-m-d',time()), 'color'=>'#173177'),
            'keyword2'=>array('value'=>$findRes['data']['title'], 'color'=>'#173177'),
            'remark'=>array('value'=>'请等待门店处理', 'color'=>'#173177'),
        ];
        \wechatUtil\TemplateMessage::sendTemplateMessage($data4,$openid,$template_id);

        $findUserRes = $userModel->findUser(['id' => $findRes['data']['uid']]);
        $openid = $findUserRes['data']['account'];
        $username = $findMemberRes['data']['username'].'(昵称：'.$findUserRes['data']['nick_name'].')';
        // 给门店发送模板消息
        $data4 = [
            'first'=>array('value'=>'缘份驿站提醒您，有新的订单！', 'color'=>'#173177'),
            'keyword1'=>array('value'=>$code, 'color'=>'#173177'),
            'keyword2'=>array('value'=>$username, 'color'=>'#173177'),
            'keyword3'=>array('value'=>'栏目认证', 'color'=>'#173177'),
            'keyword4'=>array('value'=>date('Y-m-d',time()), 'color'=>'#173177'),
            'keyword5'=>array('value'=>$findRes['data']['title'], 'color'=>'#173177'),
            'remark'=>array('value'=>'记得做好准备工作', 'color'=>'#173177'),
        ];
        \wechatUtil\TemplateMessage::sendTemplateMessage($data4,$openid,$template_id);
        // 更新订单门店信息
        $orderModel->updateOrder(['id' => $order_id] , [
            'store_id' => $store_id,
            'distribute_time' => Common::getTime()
        ]);

        echo json_encode(Common::errorArray(0,'分配成功',true));die();
    }

    /**
     * Info: 上传VCR视频
     * Date: 2022/11/9 16:09
     * 1 当用户在线上支付了视频认证费用之后，后台会收到一笔视频认证的订单，后台点击分配，弹框将平台所有的门店列出来，
     * 门店按照举例位置远近进行排序展示，显示门店的城市，举例等
     * 2 后台点击某个门店，将订单分配给门店。
     * 3 门店端接收到订单之后，点击接单且安排线下对接拍摄
     * 4 拍摄好用户的视频vcr之后，将视频文件发给总部，且在订单中心中点击已完成，
     * 总部通过后台找到该用户，进行视频认证，上传vcr视频。
     */
    function uploadVcr()
    {
        $this->getSetMenu($this);
        return $this->fetch('Order/uploadVcr/uploadVcr');
    }

    /**
     * Info: 添加红娘VCR视频
     * Date: 2022/11/9 16:09
     */
    function addVcr ()
    {
        $order_id = input('order_id',0);
        $store_id = input('store_id',0);
        $type = input('type',0);

        $orderModel = new LibOrder();
        $findRes = $orderModel->findOrder(['id' => $order_id]);
        if ($findRes['errorCode'] == 1) {
            echo json_encode(Common::errorArray(1,'订单不存在',false));die();
        }

        $user_id = $findRes['data']['user_id'];

        $memberModel = new LibMember();
        $findMemberRes = $memberModel->findMember(['user_id' => $user_id]);
        if ($findMemberRes['errorCode'] == 1) {
            echo json_encode(Common::errorArray(1, '用户不存在', []));
            die;
        }

        if (!$findRes['data']['store_id']) {
            echo json_encode(Common::errorArray(1,'尚未分配门店',false));die();
        }

        $storeModel = new LibStore();
        $findRes = $storeModel->findStore(['id' => $store_id]);
        if ($findRes['errorCode'] == 1) {
            echo json_encode(Common::errorArray(1,'门店不存在',false));die();
        }

        $vcrModel = new LibUserVideoAuth();
        //上传视频封面
        $result = $vcrModel->uploadVcrImgs();
        $imgs = '';
        if ($result['errorCode'] == 0) {
            $imgs = $result['data']['path'];
        } elseif ($result['errorCode'] == 1) {
            echo json_encode(Common::errorArray(1, $result['errorInfo'], []));
            die;
        }

        // 添加vcr视频
        $res = $vcrModel->addUserVideoAuth([
            'user_id' => $user_id,
            'order_id' => $order_id,
            'imgs' => $imgs,
            'video_url' => input('video_url'),
            'add_time' => Common::getTime(),
            'type' => $type
        ]);

        $arr = [];
        // 更新状态
        if ($type == 0 || $type == 1) {
            $arr = ['is_vip_video' => $res['data']];//普通会员或者VIP会员视频认证
        } else if ($type == 2) {
            if ($findMemberRes['data']['sex'] == '女') {
                $marriage = '签约红娘';
            } else {
                $marriage = '签约月老';
            }
            $arr = [
                'is_red_mother_video' => $res['data'],
                'marriage' => $marriage
            ];//红娘视频认证
        }
        $arr && (new LibMember())->updateMember(['user_id' => $user_id] , $arr);

        echo json_encode(Common::errorArray(0, '上传成功', true));
        die;
    }

    /**
     * Info: 模拟一元订单支付成功
     * Date: 2022/11/15 18:47
     */
    function notifyByOneYuanOrder ()
    {
        $id = input('id');
        $model = new LibOrder();
        $findRes = $model->findOrder(['id' => $id]);
        $orderModel = new LibOrderOneYuan();
        $orderFindRes = $orderModel->findOrder(['order_id' => $id]);
        $rawOrderNum = $findRes['data']['code'];
        $total_fee = $orderFindRes['data']['amount'];
        $transaction_id = time();
        $result = (new LibNotifyPay($rawOrderNum,$total_fee,$transaction_id))->orderByOneYuanSeeVideo();
        echo json_encode($result);
        die;
    }

    /**
     * Info: 模拟vip套餐支付成功
     * Date: 2022/11/15 18:47
     */
    function notifyByVipPackageOrder ()
    {
        $id = input('id');
        $model = new LibOrder();
        $findRes = $model->findOrder(['id' => $id]);
        $orderModel = new LibOrderVip();
        $orderFindRes = $orderModel->findOrder(['order_id' => $id]);
        $rawOrderNum = $findRes['data']['code'];
        $total_fee = $orderFindRes['data']['amount'];
        $transaction_id = time();
        $result = (new LibNotifyPay($rawOrderNum,$total_fee,$transaction_id))->orderByVip();
        echo json_encode($result);
        die;
    }

    /**
     * Info: 模拟视频认证支付成功
     * Date: 2022/11/15 18:47
     */
    function notifyByVipAuthOrder ()
    {
        $id = input('id');
        $model = new LibOrder();
        $findRes = $model->findOrder(['id' => $id]);
        $orderModel = new LibOrderVipAuth();
        $orderFindRes = $orderModel->findOrder(['order_id' => $id]);
        $rawOrderNum = $findRes['data']['code'];
        $total_fee = $orderFindRes['data']['amount'];
        $transaction_id = time();
        $result = (new LibNotifyPay($rawOrderNum,$total_fee,$transaction_id))->orderByVipAuth();
        echo json_encode($result);
        die;
    }

    /**
     * Info: 模拟红娘认证支付成功
     * Date: 2022/11/15 18:47
     */
    function notifyByRedMotherAuthOrder ()
    {
        $id = input('id');
        $model = new LibOrder();
        $findRes = $model->findOrder(['id' => $id]);
        $orderModel = new LibOrderRedMother();
        $orderFindRes = $orderModel->findOrder(['order_id' => $id]);
        $rawOrderNum = $findRes['data']['code'];
        $total_fee = $orderFindRes['data']['amount'];
        $transaction_id = time();
        $result = (new LibNotifyPay($rawOrderNum,$total_fee,$transaction_id))->orderByRedMotherAuth();
        echo json_encode($result);
        die;
    }

    /**
     * Info: 订单完成
     * Date: 2022/11/17 13:41
     */
    function orderFinish ()
    {
        $order_id = input('order_id');
        $model = new LibOrder();
        $findRes = $model->findOrder(['id' => $order_id]);
        if ($findRes['errorCode'] == 0) {
            $rawOrderNum = $findRes['data']['code'];
            $total_fee = $findRes['data']['pay_amount'];
            $transaction_id = $findRes['data']['transaction_id'];
            $orderNotifyModel = new LibNotifyPay($rawOrderNum,$total_fee,$transaction_id);
            $result = $orderNotifyModel->adminClickOrderCompleteBtnByVipAuth();
            echo json_encode($result);
            die;
        }
    }

    /**
     * Info: 获取分销详情
     * Date: 2022/11/17 15:58
     */
    function getUserDistributeInfo ()
    {
        $this->getSetMenu($this);
        $order_id = input('id');
        $model = new LibOrder();
        $findRes = $model->findOrder(['id' => $order_id]);
        $html = '';
        if ($findRes['errorCode'] == 0) {
            $method = [
                'getOrderDistributeByOneYuan',
                'getOrderDistributeByVip',
                'getOrderDistributeByVipAuth',
                'getOrderDistributeByRedMotherAuth'
            ];
            $result = call_user_func(['app\common\model\hfztcy\LibOrder',$method[$findRes['data']['type']]],$findRes['data']);

            foreach ($result as $item) {
                if (empty($item)) {
                    continue;
                }
                $identity_text = '';
                if (isset($item['identity'])) {
                    // 会员身份
                    $memberIdentity = [
                        '游客',
                        '注册用户',
                        'vip会员',
                        '红娘',
                        '门店'
                    ];
                    // 身份
                    $identityList = explode(',', $item['identity']);
                    $identityList = array_map('intval', $identityList);
                    foreach ($memberIdentity as $k => $v) {
                        if (!in_array($k, $identityList)) {
                            unset($memberIdentity[$k]);
                        }
                    }
                    $identity_text = implode(" ", $memberIdentity);
                }

                $info = isset($item['username']) ? $item['username'] : '';
                if ($identity_text) {
                    $info = $item['username'].'['.$identity_text.']';
                }
                $html .= <<< HTML
<tr><td style="width: 100px;text-align: center;">{$item['describe']}</td><td>{$info}</td><td>{$item['amount']}</td></tr>
HTML;
            }
        }
        $this->assign('html',$html);
        return $this->fetch("Order/distributeInfo/distributeInfo");
    }

    /**
     * Info: 删除栏目认证视频
     * Date: 2023/2/23 15:28
     */
    function deleteVideoUrl(){
        $video_url = input('video_url');
        @unlink($video_url);
        $result['errorCode'] = 0;
        echo json_encode($result);
    }

    /**
     * Info: 红娘退款
     * Date: 2023/2/23 15:29
     */
    function refundOrderByRedMother ()
    {
        $orderId = input('order_id');
        $orderSubModel = new LibOrderRedMother();
        $findOrderSubRes = $orderSubModel->findOrder(['order_id' => $orderId]);
        if ($findOrderSubRes['errorCode'] == 1) $this->sendFail('用户未支付红娘费用');
        $refundModel = new LibOrderRefund();
        $code = $refundModel->generateOrderNum();
        $findRefundRes = $refundModel->findRefund(['user_id' => $findOrderSubRes['data']['user_id'],'type' => 2]);
        if ($findRefundRes['errorCode'] == 0) if ($findRefundRes['data']['audit_state'] == 1 && $findRefundRes['data']['refund_state'] == 1) $this->sendFail('已退款');
        $refundModel->addRefund([
            'code' => $code,
            'user_id' => $findOrderSubRes['data']['user_id'],
            'add_time' => Common::getTime(),
            'type' => 2
        ]);
        echo json_encode(Common::errorArray(0,'请在“红娘退款订单”处理退款',true));die();
    }

    /**
     * Info: 栏目认证退款
     * Date: 2023/2/23 15:29
     */
    function refundOrderByVideo ()
    {
        $orderId = input('order_id');
        $orderSubModel = new LibOrderRedMother();
        $findOrderSubRes = $orderSubModel->findOrder(['order_id' => $orderId]);
        if ($findOrderSubRes['errorCode'] == 1) $this->sendFail('用户未支付栏目认证费用');
        $refundModel = new LibOrderRefund();
        $code = $refundModel->generateOrderNum();
        $findRefundRes = $refundModel->findRefund(['user_id' => $findOrderSubRes['data']['user_id'],'type' => 1]);
        if ($findRefundRes['errorCode'] == 0) if ($findRefundRes['data']['audit_state'] == 1 && $findRefundRes['data']['refund_state'] == 1) $this->sendFail('已退款');
        $refundModel->addRefund([
            'code' => $code,
            'user_id' => $findOrderSubRes['data']['user_id'],
            'add_time' => Common::getTime(),
            'type' => 1
        ]);
        echo json_encode(Common::errorArray(0,'请在“栏目认证退款订单”处理退款',true));die();
    }
}

?>